﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Net.Mail;
using System.Configuration;
using System.Text;
using OTS.BLL;
using System.Web.Configuration;

public partial class SysManage_AutoSentEmailTest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }

    public void ExportExcelSentEmail(ExportExcelModel model)
    {
        DataTable dt = model.excelDataSourceDT;
        if (dt != null && dt.Rows.Count > 0)
        {
            int nStart = 0, nEnd = 0, nLengt = dt.Rows.Count;
            nEnd = nLengt;
            List<List<string>> userEmailExcelList = new List<List<string>>();
            OTS.Common.CommonMethod.DirectoryCheck(WebConfigurationManager.AppSettings["exportExcelPosition"]);
            string fileName = WebConfigurationManager.AppSettings["exportExcelPosition"]
                + System.DateTime.Now.ToString("yyyyMMddhhmmss");

            while (nStart < nEnd)
            {
                #region 导出Excel
                nEnd = EndPosition(nStart, dt, "UserShowName");
                model.nEnd = nEnd + 1;
                model.nStart = nStart;
                model.exportAllDT = false;
                model.path = fileName + dt.Rows[nStart]["UserShowName"].ToString() + ".xls";

                CommonMethod.ExportExcel(model);

                List<string> userEmailExcel = new List<string>();
                userEmailExcel.Add(dt.Rows[nStart]["UserShowName"].ToString());
                userEmailExcel.Add(dt.Rows[nStart]["UserEmail"].ToString());
                userEmailExcel.Add(fileName + dt.Rows[nStart]["UserShowName"].ToString() + ".xls");

                userEmailExcelList.Add(userEmailExcel);

                nStart = nEnd + 1;
                nEnd = nLengt;
                #endregion
            }
            //发送邮件
            if (userEmailExcelList != null && userEmailExcelList.Count > 0)
            {
                SentEmail(userEmailExcelList);
            }
        }
    }

    public int EndPosition(int m, DataTable dt, string columnName)
    {
        int n = m - 1;
        string sono = dt.Rows[m][columnName].ToString();
        for (int i = m; i < dt.Rows.Count; i++)
        {
            n++;
            if (!sono.Equals(dt.Rows[i][columnName]))
                break;
        }

        return n;
    }

    public void SentEmail(List<List<string>> UserEmailExcel)
    {
        string exportPath = WebConfigurationManager.AppSettings["exportExcelPosition"];
        foreach (List<string> oneUserEmailExcel in UserEmailExcel)
        {
            EmailContent emailContent = new EmailContent();
            MailMessage mailObj = new MailMessage();
            
            string StrFrom = WebConfigurationManager.AppSettings["publicEmail"];
            string StrPwd = WebConfigurationManager.AppSettings["publicEmailPWD"];
            //发件人名
            string StrFromPerson = "Admin";
            //收件人
            string StrToPerson = oneUserEmailExcel[0];
            string date = System.DateTime.Now.ToString("yyyy-MM-dd");
            string time = System.DateTime.Now.ToString("yyyy-MM-dd hh:mm");
            string contractNo = string.Empty;
            string soNo = string.Empty;
            // 添加发件人
            mailObj.From = new MailAddress(StrFrom);
            mailObj.To.Add("tsu@shinfomelody.com");
            mailObj.CC.Add("Ocean.He@itt.com");
            Log.WritLog(StrFrom, System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

            //附件路径
            string file = oneUserEmailExcel[2].ToString();
            Attachment data = new Attachment(file, System.Net.Mime.MediaTypeNames.Application.Octet);
            // Add time stamp information for the file.
            System.Net.Mime.ContentDisposition disposition = data.ContentDisposition;
            disposition.CreationDate = System.IO.File.GetCreationTime(file);
            disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
            disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
            // Add the file attachment to this e-mail message.
            mailObj.Attachments.Add(data);

            #region ForTest
            mailObj.CC.Add("tsu@shinfomelody.com");
            //mailObj.CC.Add("Ocean.He@itt.com");
            #endregion

            // 发邮件
            #region
            SentEmailModel sentEmailModel = new SentEmailModel();
            sentEmailModel.ContractNoMain = "contractNo_Admin";
            sentEmailModel.UserCode = "Admin";
            sentEmailModel.EmailType = "Auto";
            sentEmailModel.EmailTypeName = "SentBySystem";

            sentEmailModel.EmailTittl = "Contracts waitting for you to deal(" + emailContent.EmailTittl2 + date + ")";
            sentEmailModel.EmailBody = string.Format("<div><div style=\"height:15px;\"></div>"
                    + "<div>Dear {0}</div> <br /><div>"
                       + " <table cellpadding=\"0\" cellspacing=\"0\">"
                      + "  <tr><td style=\"height:22px; text-align:left;\"></td></tr>"
                        + "<tr><td style=\"height:22px; text-align:left;\">有合同等你处理，详情查看附件内容。</td></tr>"
                      + "  <tr><td style=\"height:22px; text-align:left;\"></td></tr>"
                      + "  <tr><td style=\"height:22px; text-align:left;\">Best Regards.</td></tr>"
                      + "  <tr><td style=\"height:22px; text-align:left;\"></td></tr>"
                       + " <tr><td style=\"height:22px; text-align:left;\">{1}</td></tr>"
                       + " </table></div></div>",
               StrToPerson, StrFromPerson);
            #endregion

            // 邮件内容
            mailObj.Subject = sentEmailModel.EmailTittl;
            mailObj.Body = sentEmailModel.EmailBody;
            try
            {
                SentEmailBLL.SentEmail(mailObj, StrFrom, StrPwd);
                #region Email_Record
                sentEmailModel.ContractNoCust = sentEmailModel.ContractNoMain;
                sentEmailModel.EmailContent = sentEmailModel.EmailBody;
                sentEmailModel.EmailSentDate = time;
                sentEmailModel.EmailTitle = sentEmailModel.EmailTittl;
                sentEmailModel.EmailType = emailContent.EmailType;
                sentEmailModel.EmailTypeName = emailContent.EmailTypeName;
                sentEmailModel.UserCode = emailContent.UserCode;

                SentEmailBLL.EmailRecord(sentEmailModel);
                #endregion
            }
            catch { }
        }
    }

    protected void cmdAutoSentEmail_Click(object sender, EventArgs e)
    {
        lblxml.Text = "Begin...";
        Log.WritLog("Get in, Begin AutoSentEmail", System.DateTime.Now.ToString());
        AutoSentEmailSettingDAO comm = new AutoSentEmailSettingDAO();

        ExportExcelModel model = comm.GetShowColumnsAutoSentEmail();

        DataTable dt = comm.GetDataAutoSentEmail(model);
        model.excelDataSourceDT = dt;
        ExportExcelSentEmail(model);
        Log.WritLog("Get in, Begin AutoSentEmail", System.DateTime.Now.ToString());
        lblxml.Text = "End ...";
    }

    protected void cmdAutoUpdate_Click(object sender, EventArgs e)
    {
        lblxml.Text = "Begin...";
        Log.WritLog("Get in, Begin AutoUpdate", System.DateTime.Now.ToString());
        ContractInfoGetFromOtherDB comm = new ContractInfoGetFromOtherDB();
        //comm.UpdateTradingPlant();
        Log.WritLog("Get out, end AutoUpdate", System.DateTime.Now.ToString());
        lblxml.Text = "End ...";
    }

    protected void cmdFromXml_Click(object sender, EventArgs e)
    {
        lblxml.Text = CommonMethod.GetStringSimple("connectionString");
        lblxml.Text = lblxml.Text + "---" + CommonMethod.GetStringSimple("serviceName");
        lblxml.Text = lblxml.Text + "---" + CommonMethod.GetStringSimple("logPosition");
        lblxml.Text = lblxml.Text + "---" + CommonMethod.GetStringSimple("exportExcelPosition");
        lblxml.Text = lblxml.Text + "---" + CommonMethod.GetStringSimple("SentEmailService");
        lblxml.Text = lblxml.Text + "---" + CommonMethod.GetStringSimple("publicEmail");
        lblxml.Text = lblxml.Text + "---" + CommonMethod.GetStringSimple("publicEmailPWD");
    }

    protected void SentEmailTest()
    {
        MailMessage mailObj = new MailMessage();
        //string StrFrom = ConfigurationManager.ConnectionStrings["publicEmail"].ConnectionString; // "tsu@shinfomelody.com";
        //string StrPwd = ConfigurationManager.ConnectionStrings["publicEmailPWD"].ConnectionString; // "melodymelody";
        string StrFrom = "tsu@shinfomelody.com";
        string StrPwd = "melodymelody";
        //发件人名
        string StrFromPerson = string.Empty;
        //收件人
        string StrToPerson = string.Empty;

        // 添加发件人
        mailObj.From = new MailAddress(StrFrom);
        //添加邮件接收人                    
        mailObj.To.Add("tsu@shinfomelody.com");
        StrToPerson += " Test ";

        // 发邮件
        #region
        SentEmailModel sentEmailModel = new SentEmailModel();
        sentEmailModel.EmailTittl = "装箱单汇总";
        sentEmailModel.EmailBody = "Just Test";
        #endregion

        mailObj.CC.Add("tsu@shinfomelody.com");

        // 邮件内容
        mailObj.Subject = sentEmailModel.EmailTittl;
        mailObj.Body = sentEmailModel.EmailBody;
        try
        {
            SentEmailBLL.SentEmail(mailObj, StrFrom, StrPwd);
        }
        catch { CommonMethod.regAlertMessage("邮件发送失败！", this); }
    }
    protected void cmdSentEmail_Click(object sender, EventArgs e)
    {
        SentEmailTest();
    }

    protected void TiemTest()
    {
        string strTime = DateTime.Now.ToString("HH:mm:ss");
        lblxml.Text = strTime;
        if (strTime != null)
        {
            Log.WritLog("Get in,beging", strTime);
            string[] temp = strTime.Split(':');
            if (temp.Length == 3)
            {
                if (Convert.ToInt16(temp[0]) == 0 && (Convert.ToInt16(temp[1]) == 0 || (Convert.ToInt16(temp[1]) == 1 && Convert.ToInt16(temp[2]) == 0)))
                {
                    Log.WritLog("Get out, end", System.DateTime.Now.ToString());
                    lblxml.Text = " Get dddddd";
                }
                //lblxml.Text = temp[0] + "---| | ---" + temp[1] + "----| | ----" + temp[2];
            }
        }
    }
    protected void cmdTimeTest_Click(object sender, EventArgs e)
    {
        TiemTest();
    }

    protected void cmdpxLength_Click(object sender, EventArgs e)
    {
        //string temp = "sdj附件是临时fdslkfjdslfhdslk方式范德萨jfs";
        //int n="".TextWidthInPixels



    }
    /// <summary>
    /// 截取字符串指定的长度并加上省略号 以字节形式计算
    /// </summary>
    /// <param name="inputString">字符串</param>
    /// <param name="len">截取长度,以字节形式计算</param>
    /// <returns></returns>
    public static string CutStrMit(string inputString, int len)
    {
        ASCIIEncoding ascii = new ASCIIEncoding();
        int tempLen = 0;
        string tempString = "";
        byte[] s = ascii.GetBytes(inputString);
        for (int i = 0; i < s.Length; i++)
        {
            if ((int)s[i] == 63)
            {
                tempLen += 2;
            }
            else
            {
                tempLen += 1;
            }

            try
            {
                tempString += inputString.Substring(i, 1);
            }
            catch
            {
                break;
            }

            if (tempLen > len)
                break;
        }
        //如果截过则加上半个省略号
        byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);
        if (mybyte.Length > len)
            tempString += "...";

        return tempString;
    }
    protected void cmdSubstring_Click(object sender, EventArgs e)
    {
        txt.Visible = true;

        txt.Text = "fsfsdfffffffhf/".Substring(0, "fsfsdfffffffhf/".Length - 1);
        txt.Text = "R-v987999DDDL973".Substring(1, 2).ToUpper().Equals("-V").ToString();
        
    }
}